#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File        :PDF转EXCEL.py
@Time        :2020/09/01 20:22:29
@Author      :hejiang
@Software    :vsCode
'''
'''
pip install pdfplumber  # 为了操作PDF
pip install xlwt        # 为了操作Excel
'''


import pdfplumber
import xlwt
import os
workbook = xlwt.Workbook()  # 定义workbook
sheet = workbook.add_sheet('Sheet1')  # 添加sheet
i = 0  # Excel起始位置

path = input("请输入PDF文件位置：")

output_dir = os.path.split(path)[0]
file_name = os.path.split(path)[1].split('.')[0] + ".xls"

# path = "aaaaaa.PDF"  # 导入PDF路径
pdf = pdfplumber.open(path)
print('\n')
print('开始读取数据')
print('\n')
for page in pdf.pages:
    # 获取当前页面的全部文本信息，包括表格中的文字
    # print(page.extract_text())
    for table in page.extract_tables():
        # print(table)
        for row in table:
            print(row)
            for j in range(len(row)):
                sheet.write(i, j, row[j])
            i += 1
        print('---------- 分割线 ----------')

pdf.close()


# C:\Users\He\Desktop\伟星PP-R价格表（灰）20180101.pdf

out_url = os.path.join(output_dir, file_name)
# 保存Excel表
workbook.save(out_url)
print('\n')
print('写入excel成功')
print('保存位置：')
print(out_url)
print('\n')
input('PDF取读完毕，按任意键退出')
